package com.example.scrambledpuzzle;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.ImageColumns;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;

import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import android.util.Log;

import android.view.DragEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.DragShadowBuilder;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;

import android.widget.GridView;
import android.widget.ImageView;

import android.widget.TextView;

public class SwapPuzzle extends Activity {
	Integer[] resourcePics={
			R.drawable.cow,
			R.drawable.dog ,
			R.drawable.elephant,
			R.drawable.fish,
			R.drawable.fox,
			R.drawable.peacock,
			//R.drawable.beavers,
			//R.drawable.bike,
			//R.drawable.car

	};
	PuzzleLogic mPuzzleLogic= new PuzzleLogic(this);
	boolean fromGallery=false;


	TextView  txtNoOfMoves;
	GridView gdView;
	int resId,rnd;
	int ctr=0;

	//Bitmap scratch;
	int ctrNoOfMoves=0;
	String key;
	/// Tag for logging
	private static final String TAG = "PuzzleActivity";




	//List<Integer> mResourcePicsList=new ArrayList<Integer>();
	List<Integer> mResourcePicsList= Arrays.asList(resourcePics);


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_puzzle);

		//cr =getContentResolver();
		ImageView rightArrow=(ImageView) findViewById(R.id.right);
		txtNoOfMoves=(TextView) findViewById(R.id.displayNoOfMoves);

		ImageView homeButton = (ImageView) findViewById(R.id.home);


		resId=getIntent().getIntExtra("BitmapImage", 0);
		String path=getIntent().getExtras().getString("CameraPath");
		final Uri uriPath=getIntent().getExtras().getParcelable("GalleryPath");

		fromGallery=mPuzzleLogic.initializePuzzleLogic(resId,path, uriPath,fromGallery);


		//Create GridView
		gdView=(GridView) findViewById(R.id.gridviewToAssemble);
		//Create the adapter of GridView
		//Log.v(TAG,"coming to gridadapter");
		gdView.setAdapter(new GridAdapter(this));

		gdView.setOnTouchListener(new OnTouchListener(){

			@Override
			public boolean onTouch(View arg1, MotionEvent event) {
				if(event.getAction()==MotionEvent.ACTION_DOWN){


					GridView parent=(GridView)arg1;
					int x = (int) event.getX();
					int y = (int) event.getY();


					int position = parent.pointToPosition(x, y);
					ImageView viewToBeDragged=(ImageView) parent.getChildAt(position);

					if (viewToBeDragged.getTag() != null){

						ClipData.Item item=new ClipData.Item((CharSequence)viewToBeDragged.getTag().toString());
						ClipDescription NOTE_STREAM_TYPES= new ClipDescription ((CharSequence)viewToBeDragged.getTag().toString(),new String[ ] {ClipDescription.MIMETYPE_TEXT_PLAIN});
						ClipData clipData=new ClipData(NOTE_STREAM_TYPES,item);
						clipData.addItem(item);
						DragShadowBuilder shadowBuilder=new  View.DragShadowBuilder(viewToBeDragged);
						viewToBeDragged.startDrag(clipData, shadowBuilder, viewToBeDragged, 0);


						return true;
					}else{

						return false;
					}
				}
				return true;
			}

		});

		gdView.setOnDragListener(new View.OnDragListener() {

			@Override
			public boolean onDrag(View v, DragEvent event) {

				//int action=event.getAction();
				switch(event.getAction()) {
				case DragEvent.ACTION_DRAG_STARTED:
					break;
				case DragEvent.ACTION_DRAG_ENTERED:
					break;
				case DragEvent.ACTION_DRAG_EXITED:

					break;
				case DragEvent.ACTION_DROP:

					GridView parent=(GridView) v;
					GridAdapter adapter=(GridAdapter) parent.getAdapter();
					int x=(int)event.getX();
					int y=(int) event.getY();
					int position=parent.pointToPosition(x, y);
					int relativePosition=position-parent.getFirstVisiblePosition();

					ImageView dragged=(ImageView) event.getLocalState();

					ImageView dropped=(ImageView)parent.getChildAt(relativePosition);

					if(dragged !=null){
						if (position>AdapterView.INVALID_POSITION){
							int dropLocationIndex=(Integer) dropped.getTag();
							int imageindex=(Integer)dragged.getTag();

							int draggedCellPosition=mPuzzleLogic.mGalleryList.indexOf(imageindex);
							ImageView draggedCell=(ImageView) parent.getChildAt(draggedCellPosition);

							mPuzzleLogic.dropHandler(dropLocationIndex, imageindex);

							dropped.setImageBitmap(mPuzzleLogic.mBmpPieces[imageindex]);
							dropped.setTag(imageindex);
							draggedCell.setImageBitmap(mPuzzleLogic.mBmpPieces[dropLocationIndex]);

							draggedCell.setTag(dropLocationIndex);

							if(dropLocationIndex != imageindex){
								ctrNoOfMoves++;
								txtNoOfMoves.setText( Integer.toString( ctrNoOfMoves ));
							}	
							adapter.notifyDataSetChanged();
							boolean playsSound=mPuzzleLogic.activateSound();
							if(playsSound) disableChildsOnTouch(parent);
							
						}
					}

					break;
				case DragEvent.ACTION_DRAG_ENDED:
					mPuzzleLogic.playSound(R.raw.cluck);

					break;
				}
				return true;


			}

			private void disableChildsOnTouch(GridView parent) {
				int cnt=parent.getChildCount();
				for(int i=0;i<cnt;i++){
					View v=parent.getChildAt(i);
					if(v instanceof GridView){
						disableChildsOnTouch((GridView) v);
					}else{
						v.setOnTouchListener(null);
			            v.setOnClickListener(null);
					}
				}
				
			}

		});


		homeButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent homeScreen=new Intent(SwapPuzzle.this,PhoneGalllery.class);

				startActivity(homeScreen);
				finish();

			}
		});

		rightArrow.setOnClickListener(new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				int resourceId;
				//scratch=null;
				mPuzzleLogic.destroyReferences();
				if(fromGallery){
					fromGallery=mPuzzleLogic.initializePuzzleLogic(0, null, null, true);


				}
				else{

					if(ctr >= mResourcePicsList.size()) {

						ctr=0;
					}
					resourceId=mResourcePicsList.get(ctr);
					ctr++;
					fromGallery=mPuzzleLogic.initializePuzzleLogic(resourceId, null, null, false);
					//scratch=BitmapFactory.decodeResource(getResources(),resourceId);

				}
				ctrNoOfMoves=0;
				txtNoOfMoves.setText("");
				//resizeBitmap();
				//mGalleryList.clear();

				//createBitmapPieces(scratch);
				gdView.setAdapter(new GridAdapter(SwapPuzzle.this));


			}

		});

	}

	protected void onDestroy(){
		Log.v(TAG,"Destroying objects");
		mPuzzleLogic.destroyReferences();
		super.onDestroy();
	}






	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.puzzle, menu);
		return true;
	}

}


